﻿using System;
using System.Web.Mvc;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Web;
using System.Drawing.Imaging;

namespace MvcShop.Extensions
{
    public class CaptchaImageActionResult : ActionResult
    {
        public Color BackGroundColor { get; set; }
        public Color RandomTextColor { get; set; }
        public string RandomWord { get; set; }

        public override void ExecuteResult(ControllerContext context)
        {
            RenderCaptchaImage(context);
        }
        public void RenderCaptchaImage(ControllerContext context)
        {
            Bitmap bitMapImage = new Bitmap(150, 60);
            Graphics g = Graphics.FromImage(bitMapImage);
            g.Clear(BackGroundColor);

            SolidBrush objBrush = new SolidBrush(RandomTextColor);
            SolidBrush objBrush1 = new SolidBrush(BackGroundColor);
            g.FillRectangle(objBrush1, 0, 0, 150, 60);
            //g.FillRectangle(objBrush, 0, 0, 150, 60);
            g.SmoothingMode = SmoothingMode.HighSpeed;
            Font objFont = null;
            String myFont, str;
            int a;

            String[] crypticFonts = new String[11];
            crypticFonts[0] = "Arial";
            crypticFonts[1] = "Verdana";
            crypticFonts[2] = "Comic Sans MS";
            crypticFonts[3] = "Impact";
            crypticFonts[4] = "Garamond";
            crypticFonts[5] = "Courier New";
            crypticFonts[6] = "Arial Narrow";
            crypticFonts[7] = "Book Antiqua";
            crypticFonts[8] = "Haettenschweiler";
            crypticFonts[9] = "Wen Hao";
            crypticFonts[10] = "Yeaszi";

            for (a = 0; a <= RandomWord.Length - 1; a++)
            {
                myFont = crypticFonts[new Random().Next(a)];
                objFont = new Font(myFont, 18, FontStyle.Bold | FontStyle.Italic | FontStyle.Strikeout);
                str = RandomWord.Substring(a, 1);
                g.DrawString(str, objFont, objBrush, a * 20, 20);
            }

            Random r = new Random();
            for (int i = 0; i < 220; i++)
            {
                int x = r.Next(bitMapImage.Width);
                int y = r.Next(bitMapImage.Height);
                bitMapImage.SetPixel(x, y, Color.FromArgb(r.Next(0, 255), r.Next(0, 255), r.Next(0, 255)));
            }
            HttpContext.Current.Response.ContentType = "image/jpeg";
            HttpContext.Current.Response.Cache.SetNoStore();//设置不在页面缓存
            bitMapImage.Save(HttpContext.Current.Response.OutputStream, ImageFormat.Jpeg);
            objFont.Dispose();
            g.Dispose();
            bitMapImage.Dispose();
        }
    }
}
